<template>
  <div>
<!--    搜索，新增-->
    <div style="margin-bottom: 15px">
      <el-input style="width: 200px;margin-right: 5px;" v-model="params.userName" placeholder="请输入姓名"></el-input>
      <el-input style="width: 200px" v-model="params.identity" placeholder="请输入身份"></el-input>
      <el-button type="warning" style="margin-left: 10px" size="small" @click="findBySearchOfUsers()">查询</el-button>
      <el-button type="info" style="margin-left: 10px" size="small" @click="reset()">清空</el-button>
      <el-button type="primary" style="margin-left: 10px" size="small" @click="add()">新增</el-button>
      <el-popconfirm v-if="user.identity === 'admin'" title="确定删除这些数据吗？" @confirm = removeBatch()>
        <el-button style="margin-left: 5px;" slot="reference" type="danger" size="small">批量删除</el-button>
      </el-popconfirm>
    </div>

    <!--    表格-->
    <div>
      <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column prop="img" label="头像">
          <template v-slot="scope">
            <el-image
                style="width: 70px; height: 70px; border-radius: 50%"
                :src="'http://localhost:8088/api/files/' + scope.row.img"
                :preview-src-list="['http://localhost:8088/api/files/' + scope.row.img]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="成员ID"></el-table-column>
        <el-table-column prop="userName" label="成员姓名" ></el-table-column>
        <el-table-column prop="identity" label="成员身份"></el-table-column>
        <el-table-column prop="deviceNames" label="设备权限">
          <template v-slot="scope">
            <span v-if="scope.row.deviceNames && scope.row.deviceNames.length">
              {{ scope.row.deviceNames.join(', ') }}
            </span>
            <span v-else>无设备</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" ></el-table-column>

        <el-table-column  label="操作">
          <template v-slot="scope">
<!--            scope.row 将这一行的数据返回-->
            <el-button style="margin-right: 5px;" type="primary" size="small" @click="edit(scope.row)" :disabled="!canEdit(scope.row)">编辑</el-button>

            <el-popconfirm title="确定删除吗？" @confirm = remove(scope.row.userId)>
              <el-button  slot="reference" type="danger" size="small" :disabled="!canEdit(scope.row)">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

<!--    新增，编辑对话框-->
    <div>
      <el-dialog title="请填写信息" :visible.sync="dialogFormVisible">
        <el-form :model="form">
          <el-form-item label="头像" label-width="15%">
            <el-upload action="http://localhost:8088/api/files/upload" :on-success="successUpload">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="身份" label-width="15%">
            <el-radio v-model="form.identity" label="家长">家长</el-radio>
            <el-radio v-model="form.identity" label="孩子">孩子</el-radio>
          </el-form-item>
          <el-form-item label="姓名" label-width="15%">
            <el-input v-model="form.userName" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
          <el-form-item label="密码" label-width="15%" v-if="form.canEditPassword">
            <el-input v-model="form.password" autocomplete="off" style="width: 90%"></el-input>
          </el-form-item>
<!--          选择器，用户选择可查看权限-->
          <el-form-item label="可查看权限" label-width="15%">
            <el-select v-model="form.deviceIds" multiple placeholder="请选择设备" style="width: 90%">
              <el-option v-for="item in deviceTypes" :key="item.deviceId" :label="item.deviceName" :value="item.deviceId"></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit()">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <!--    分页功能-->
    <div style="margin-top: 15px; text-align: center">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 15,20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
//引入封装好的request
import request from "@/utils/request";

export default {
  name: 'P_UsersManagement',
  data() {
    return {
      params:{
        userName: '',
        identity: '',
        pageNum: 1, //当前页
        pageSize: 5 //当前页大小
      },
      tableData: [],
      deviceTypes:[],
      total: 0,
      dialogFormVisible: false,
      form:{
        deviceIds:[],
      },
      multipleSelection: [],
      user:localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {},
    }
  },
  //页面加载时进行的操作
  created() {
    this.findBySearchOfUsers();
    this.findAllDevices();
  },
  methods: {
    // 查找所有设备信息，并将所有设备设备信息存放在deviceTypes数组中
    findAllDevices(){
      request.get("Devices/findAllDevices").then(res => {
        if(res.code === '0'){
          this.deviceTypes = res.data;
          console.log("所有的设备：", this.deviceTypes);
        }else{
          this.$message.error(res.msg);
        }
      })
    },
    findBySearchOfUsers(){
      request.get("Users/findBySearchOfUsers",{params:this.params}).then(res => {
        console.log("执行findBySearchOfUsers请求时，前端传递给后端的参数：",this.params);
        if(res.code === '0'){
          this.tableData = res.data.list;
          this.total = res.data.total;
          console.log("后端执行findBySearchOfUsers方法后，返回给前端的数据：",res.data);

        }else{

        }
      })
    },

    reset(){
      this.params = {
        userName:'',
        identity:'',
        pageNum: 1,
        pageSize: 5
      }
      this.findBySearchOfUsers();
    },
    add(){
      console.log("有没有旧数据",this.form.img)
      this.form = {}; //清空表单内容
      this.form.canEditPassword = true;
      this.dialogFormVisible = true;
    },
    submit(){
      request.post("Users/saveUser", this.form).then(res => {
        if(res.code === '0'){
          //在控制台查看是否获取到选中设备的deviceId
          console.log("选中设备Id：",this.form.deviceIds);
          console.log("传递给后台的表单信息：",this.form);
          this.$message({
            message: '操作成功',
            type: 'success',
          });
          this.form = {};
          this.dialogFormVisible = false;
          this.findBySearchOfUsers();
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          });
          this.form = {};
          this.dialogFormVisible = true;
        }
      })
    },
    canEdit(user) {
      const currentUserId = this.getCurrentUserId(); // 获取当前用户ID
      const currentUserIdentity = this.getCurrentUserIdentity(); // 获取当前用户身份

      const isAdmin = currentUserIdentity === "admin"; // 判断是否是admin
      const isCurrentUser = user.userId === currentUserId; // 判断是否是当前用户
      const isChild = user.identity === "孩子"; // 判断目标用户是否是孩子
      const isParent = currentUserIdentity === "家长"; // 判断当前用户是否是家长

      // admin 可以编辑所有人
      if (isAdmin) {
        return true;
      }
      // 家长只能编辑自己和孩子
      if (isParent && (isCurrentUser || isChild)) {
        return true;
      }
      // 其他情况（如家长想编辑其他家长）
      return false;
    },
    edit(data) {
      const userId = data.userId; // 从 data 中获取 userId
      request.get("Users/findDeviceIdsByUserId/" + userId).then(res => {
        console.log("findDeviceIdsByUserId方法已调用这里应该是后端查找出来的existDeviceIds");
        this.form.deviceIds = res.data;
        console.log("这里应该是后端查找出来的existDeviceIds:" ,this.form.deviceIds);
      })
      console.log("从后台带出的内容：",data);
      if (!this.canEdit(data)) {
        this.$message.error("无权编辑该用户！");
        return;
      }
      const currentUserId = this.getCurrentUserId(); // 获取当前登录用户 ID
      const currentUserIdentity = this.getCurrentUserIdentity(); // 获取当前用户身份
      const isAdmin = currentUserIdentity === "admin"; // 是否为 admin
      const isCurrentUser = data.userId === currentUserId; // 判断是否是当前用户
      const isChild = data.identity === "孩子"; // 目标用户是否是孩子
      const isParent = currentUserIdentity === "家长"; // 当前用户是否是家长

      this.form = Object.assign({}, data);

      // 确保 img 字段被正确赋值
      if (!this.form.img) {
        this.form.img = ""; // 如果 img 为空，赋值为空字符串，避免显示上次的图片
      }

      // 只有 admin 可以查看所有人的密码
      if (isAdmin) {
        this.form.password = data.password !== null ? data.password : "123456";
        this.form.canEditPassword = true;
      }
      // 家长只能查看和修改自己的密码或孩子的密码
      //如果当前用户是 家长，且要编辑的对象是自己 (isCurrentUser) 或 孩子 (isChild)，就允许查看和修改密码。
      else if (isParent && (isCurrentUser || isChild)) {
        this.form.password = data.password || "123456";
        this.form.canEditPassword = true;
      }
      // 家长不能查看或修改其他家长的密码
      //如果当前用户是 家长，但想查看 其他家长的密码，不允许。
      else if (isParent && data.identity === "家长") {
        this.form.password = ""; // 其他家长的密码不可见
        this.form.canEditPassword = false;
      }
      this.dialogFormVisible = true;
    },
    remove(userId){
      console.log("要删除的userId：" ,userId);
      const userToDelete = this.tableData.find(user => user.userId === userId);
      if (!this.canEdit(userToDelete)) {
        this.$message.error("无权删除该用户！");
        return;
      }
      request.delete("Users/deleteUser/" + userId).then(res => {
        if(res.code === '0'){
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.findBySearchOfUsers();
        }else{
          this.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    removeBatch(){
      if(this.multipleSelection.length === 0){
        this.$message.warning("请选择要删除的项！");
        return;
      }
      console.log("批量删除选中的数据 ",this.multipleSelection);
      request.put("/Users/deleteBatch",this.multipleSelection).then(res =>{
        if(res.code === '0'){
          this.$message.success("批量删除成功！");
          this.findBySearchOfUsers();
        }else{
          this.$message.error(res.msg);
        }
      })
    },
    //批量删除
    handleSelectionChange(val){
      this.multipleSelection = val;
    },
    successUpload(res){
      this.form.img = res.data;
    },
    getCurrentUserId() {
      return JSON.parse(localStorage.getItem("user"))?.userId;
    },
    getCurrentUserIdentity() {
      return JSON.parse(localStorage.getItem("user"))?.identity;
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.findBySearchOfUsers();
    },
    handleCurrentChange(pageNum) {
      this.params.pageNum = pageNum;
      this.findBySearchOfUsers();
    },
  }
}
</script>